﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Interfaces.Presenter_Interfaces;
using Interfaces.General_Interfaces;
using Presenters.Inherited_Presenters;
using System.IO.Ports;
using System.Timers;
using Presenters.Other_Class;
using System.Linq;
using GpsUtil;

namespace Presenters.General_Presenters
{
    public class JobManagerPresenter:OperationStatus
    {
        private IJobManagerView view = null;
        private System.Timers.Timer timer = null;
        private ComDataReader.ComDataReader serialPort;
        private string dataFromGps = "";

        public JobManagerPresenter(IJobManagerView view)
        {
            this.view = view;
            Initialize();
        }

        private void Initialize()
        {
            timer = new Timer();
            timer.Interval = 1000;
            serialPort = new ComDataReader.ComDataReader("COM4");
            timer.Elapsed += new ElapsedEventHandler(GetDataComReader);
            timer.Enabled = true;
            timer.Start();
        }

        private void GetDataComReader(object obj, ElapsedEventArgs arg)
        {
            nameOperation = "Przesyłanie danych";
            try
            {
                dataFromGps += serialPort.dataFromGps + "\n";
                view.statusGps = dataFromGps.GetStatusGps();
                view.speed = dataFromGps.GetSpeedKnock().ToKmh();
                dataFromGps = String.Empty;
            }
            catch (Exception ex)
            {
                exception = ex.Message;
            }
        }

        public void StartListening()
        {
            nameOperation = "Otwieranie portu";
            try
            {
                serialPort.OpenPort();
            }
            catch (Exception ex)
            {
                exception = ex.Message;
                timer.Stop();
                view.ShowError();
            }
        }

        public void StopListening()
        {
            nameOperation = "Zamykanie portu";
            try
            {
                timer.Stop();
                serialPort.ClosePort();
            }
            catch (Exception ex)
            {
                exception = ex.Message;
                timer.Stop();
                view.ShowError();
            }
        }
    }
}
